package onlinebanking.server.modules;

import onlinebanking.network.Message;
import onlinebanking.server.objects.PersonalAccount;
import onlinebanking.server.objects.Session;
import onlinebanking.server.ServerEngine;
import onlinebanking.constants.*;

public class Login extends Module {

	public Login(ServerEngine se, Message message) {
		this.serverengine = se;
		this.message = message;

	}

	public Message handleRequest() {
		Message result;

		if (!serverengine.isLoggedIn()) {

			// get username and password from message
			String username = message.getString("username");
			String password = message.getString("password");

			// authenticate username and password - returns a Message result
			result = PersonalAccount.authenticateLogin(username, password);

			// if valid username and password
			if (result.getMsgType() == MSG.LOGIN_SUCCESS) {

				// create new session
				Session session = serverengine.createNewSession();
				session.setUserAccount(new PersonalAccount(username));
				result.addAttribute("username", username);
			}
		} else {
			// someone is already logged in
			result = new Message();
			result.setMsgType(MSG.LOGIN_FAILED);
			result.addAttribute("reason", "Please logout first");
		}
		return result;
	}

}
